package com.yjian.config;

import com.yjian.common.CodeMap;
import com.yjian.common.SDataResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 许小宝 on 2017/9/27.
 */
@RestControllerAdvice
public class ControllerAdviser
{

    /**
     * 参数校验异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object paramsException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<Map<String, String>> errorList = new ArrayList<>();
        for (FieldError error : fieldErrors) {
            Map<String, String> desc = new LinkedHashMap<>();
            desc.put("field", error.getField());
            desc.put("message", error.getDefaultMessage());

            errorList.add(desc);
        }
        return new SDataResult(CodeMap.PARAM_ERROR,errorList);
    }
}
